<template>
  <div class="add">
    <el-card style="padding: 20px">
      <div slot="header">
        <h2 v-show="!$route.params.detailId && !$route.params.editId">
          新增Banner
        </h2>
        <h2 v-show="$route.params.detailId">Banner详情</h2>
        <h2 v-show="$route.params.editId">编辑Banner</h2>
      </div>
      <el-form
        v-loading="loading"
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="名称" prop="title">
          <el-input
            style="width: 300px"
            :disabled="isDetail"
            v-model="ruleForm.title"
            placeholder="请填写"
          ></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="10">
            <el-form-item label="图片" prop="picUrl" required>
              <el-upload
                class="upload-demo"
                :disabled="isDetail"
                ref="upd"
                accept="image/png,image/jpeg"
                :action= setUrl
                :headers="headers"
                :on-success="successUp"
                :on-error="errorUp"
                :before-upload="beforeUpd"
              >
                <el-button :disabled="isDetail" size="small" type="primary"
                  >点击上传</el-button
                >
                <div slot="tip" class="el-upload__tip">
                  图片要求：长宽比为553：185 ，jpg/png，不大于500k
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col style="text-align: center" :span="14">
            <img :hidden="ruleForm.picUrl == ''" :src="ruleForm.picUrl" alt />
          </el-col>
        </el-row>
        <el-form-item label="banner链接">
          <el-form-item prop="url">
            <el-radio-group
              :disabled="isDetail"
              @change="selectUrl"
              v-model="ruleForm.source"
            >
              <el-radio :label="1">自定义链接</el-radio>
              <el-input
                :disabled="isDetail"
                clearable
                v-show="ruleForm.source == '1'"
                placeholder="请输入链接地址"
                style="width: 200px"
                ref="urlIpt"
                size="small"
                v-model.trim="ruleForm.url"
              ></el-input>
              <el-radio style="margin-left: 20px" :label="0">已有产品</el-radio>
              <el-input
                v-show="ruleForm.source == '0'"
                placeholder="请输入链接地址"
                clearable
                :disabled="isDetail"
                style="width: 200px"
                size="small"
                v-model.trim="ruleForm.url"
              ></el-input>
              <el-button
                v-show="ruleForm.source == '0' && ruleForm.url == ''"
                :disabled="isDetail"
                style="margin-left: 20px"
                size="small"
                type="primary"
                @click="choose"
                >请选择</el-button
              >
              <el-button
                v-show="ruleForm.source == '0' && ruleForm.url != ''"
                :disabled="isDetail"
                style="margin-left: 20px"
                size="small"
                type="primary"
                @click="change"
                >更换</el-button
              >
            </el-radio-group>
            <i class="el-icon-warning">切换需重新输入及选择,请谨慎操作!</i>
          </el-form-item>
        </el-form-item>
        <el-form-item label="展示时间" prop="showTime">
          <el-date-picker
            :disabled="isDetail"
            @change="selectTime"
            v-model="timers"
            type="datetimerange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="['00:00:00', '23:59:59']"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="showStatus">
          <el-radio-group :disabled="isDetail" v-model="ruleForm.showStatus">
            <el-radio :label="0">启用</el-radio>
            <el-radio :label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="showOrder">
          <el-input
            :disabled="isDetail"
            style="width: 360px"
            size="small"
            min="1"
            onkeyup="value=value.replace(/^(0+)|[^\d]+/g,'')"
            placeholder="整数，数字越小排序越靠前，相同数字，按照时间倒序"
            v-model="ruleForm.showOrder"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            :disabled="isDetail"
            class="ipt"
            type="textarea"
            rows="5"
            maxlength="50"
            placeholder="最多50字"
            show-word-limit
            v-model="ruleForm.remark"
          ></el-input>
        </el-form-item>
        <el-form-item v-if="!$route.params.detailId">
          <el-button type="primary" @click="submitForm('ruleForm')"
            >提交</el-button
          >
          <el-button @click="resetForm('ruleForm')">取消</el-button>
        </el-form-item>
        <el-form-item v-else>
          <el-button @click="goback('ruleForm')">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import modelApi from "@/api/lejv/banner";
import setting from "@/settings"
import { getToken } from "@/utils/auth";
import { initTime } from "@/utils/index"; //引入时间处理函数
export default {
  name: "Add",
  data() {
    var checkUrl = (rule, value, callback) => { //自定义校验规则,验证网址是否输入正确
      if (this.ruleForm.url !== "") {
        let reg = /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\/])/;
        if (!reg.test(this.ruleForm.url)) {
          return callback(new Error("请输入以http/https开头的网址!"));
        }
        callback()
      }else{
        callback()
      }
    };
    return {
      ruleForm: {
        //表格数据
        title: "",
        picUrl: "",
        setUrl:"",
        url: "",
        showTime: "",
        hideTime: "",
        showStatus: 0,
        source: 1,
        showOrder: "",
        channel: "",
        remark: "",
      },
      // img:"",
      headers: { Authorization: getToken() }, //上传图片携带token
      timers: [], //选择的时间
      loading: false, //是否显示加载动画
      isDetail: true, //查看时禁止编辑
      isSelect: false,
      rules: {
        //定义校验规则
        title: [
          { required: true, message: "请输入产品名称", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        url: [{ validator: checkUrl, trigger: "change" }],
        picUrl: [{ required: true, message: "请上传图片", trigger: "change" }],
        showStatus: [
          { required: true, message: "请选择状态", trigger: "change" },
        ],
        showOrder: [
          { required: true, message: "请填写排序数字", trigger: "blur" },
        ],
        showTime: [
          {
            required: true,
            message: "请选择日期",
            trigger: "change",
          },
        ],
      },
    };
  },
  computed: {},
  created() {
    this.setUrl = window.location.host.indexOf('tk') != -1 ? (window.location.protocol + "//" + window.location.host + "/file/image/auth") : "http://tklifeacuat.mobile.taikang.com/file/image/auth"
    // console.log('------this.setUrl', this.setUrl)
    // this.setUrl = window.location.host + "/file/image/auth"
    // this.setUrl = "http://tklifeacuat.mobile.taikang.com/file/image/auth"  //生产环境需改为https
    //判断是编辑,查看,还是新增  重点是处理编辑与新增
    //进行页面跳转时增加路由标识及存储修改数据,用来处理判断回退到哪个页面及数据渲染
    let item = JSON.parse(localStorage.getItem("pageObj"));
    if (this.$route.params.detailId) {
      this.editInfo(this.$route.params.detailId);
    } else if (this.$route.params.editId) {
      this.isDetail = false;
      // console.log(item);
      if (this.$route.params.url) {
        if (item) {
          // console.log(item);
          this.ruleForm = item; //表格数据
          // this.img = item.img
          this.ruleForm.url = this.$route.params.url; //选择的产品链接
          this.timers.push(item.showTime, item.hideTime); //显示时间
        }
        // console.log(this.$route.params.url);
      } else {
        this.editInfo(this.$route.params.editId);
      }
    } else {
      if (item) {
        this.ruleForm = item; //表格数据
        // this.img = item.img
        if (this.$route.params.url){
          this.ruleForm.url = this.$route.params.url; //选择的产品链接
          // console.log(this.$route.params.url,this.$route.params.channel);
          this.ruleForm.channel = this.$route.params.channel
        }else{
          this.ruleForm.url = ""
        }
        this.timers.push(item.showTime, item.hideTime); //显示时间
      }
      this.isDetail = false;
    }
  },
  mounted() {},
  methods: {
    //提交
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.$route.params.editId) {
            //判断是否是编辑还是新增
            let params = {
              ...this.ruleForm,
            };
            this.loading = true;
            delete params.flag;
            if (this.isSelect) {
              params.gmtCreate = initTime(params.gmtCreate);
            } else {
              params.gmtCreate = initTime(params.gmtCreate);
              params.showTime = initTime(params.showTime);
              params.hideTime = initTime(params.hideTime);
            }
            modelApi
              .updataBanner(params)
              .then((res) => {
                // console.log(res);
                if (res.msg == "success") {
                  this.$message({
                    type: "success",
                    message: "修改成功!",
                  });
                  this.isSelect = false;
                  this.loading = false;
                  this.$router.push("/content/banner");
                  this.$refs.ruleForm.resetFields();
                  localStorage.removeItem("pageObj");
                }
              })
              .catch((res) => {
                this.$message({
                  type: "error",
                  message: "修改失败!",
                });
                this.loading = false;
              });
          } else {
            let params = {
              ...this.ruleForm,
            };
            params.showTime = initTime(params.showTime);
            params.hideTime = initTime(params.hideTime);
            this.addBanner(params);
          }
        } else {
          // console.log("提交失败!");
          return false;
        }
      });
    },
    //新增产品
    addBanner(obj) {
      this.loading = true;
      modelApi.addBanner(obj).then((res) => {
        // console.log(res);
        if (res.msg == "success") {
          this.$message({
            type: "success",
            message: "添加成功!",
          });
          this.loading = false;
          this.$router.push("/content/banner");
          localStorage.removeItem("pageObj");
          this.$refs.ruleForm.resetFields();
        }
      });
    },
    //获取编辑产品信息
    editInfo(id) {
      modelApi.bannerInfo({ id }).then((res) => {
        // console.log(res);
        if (res.msg == "success") {
          this.ruleForm = res.data[0];
          // this.img = this.ruleForm.picUrl
          this.ruleForm.showStatus = Number(this.ruleForm.showStatus);
          this.ruleForm.source = Number(this.ruleForm.source);
          this.timers.push(res.data[0].showTime, res.data[0].hideTime);
        }
      });
    },
    //取消
    resetForm(formName) {
      this.$refs.ruleForm.resetFields();
      this.$router.push("/content/banner");
      localStorage.removeItem("pageObj");
    },
    //返回
    goback(formName) {
      this.$router.push("/content/banner");
      this.$refs.ruleForm.resetFields();
      localStorage.removeItem("pageObj");
    },
    //选择链接
    selectUrl(val) {
      this.$refs.urlIpt.clear();
    },
    //选择时间
    selectTime(val) {
      this.isSelect = true;
      if(val != null){
        this.ruleForm.showTime = initTime(val[0]);
        this.ruleForm.hideTime = initTime(val[1]);
      }
    },
    //选择产品
    choose() {
      //存储页面修改信息,避免跳转后数据丢失
      let pageInfo = JSON.parse(JSON.stringify(this.ruleForm));
      // pageInfo.img = this.img
      pageInfo = JSON.stringify(pageInfo);
      localStorage.setItem("pageObj", pageInfo);
      if (this.$route.params.editId) {
        this.$router.push({
          path: "/content/choose",
          query: { edit: this.$route.params.editId },
        });
      } else {
        this.$router.push("/content/choose");
      }
    },
    //更换产品
    change() {
      //存储页面修改信息,避免跳转后数据丢失
      let pageInfo = JSON.parse(JSON.stringify(this.ruleForm));
      // pageInfo.img = this.img
      pageInfo = JSON.stringify(pageInfo);
      localStorage.setItem("pageObj", pageInfo);
      if (this.$route.params.editId) {
        this.$router.push(`/content/choose?edit=${this.$route.params.editId}`);
      } else {
        this.$router.push("/content/choose");
      }
    },
    //上传图片
    successUp(val) {
      // this.ruleForm.picUrl = val.slice(49);
      // this.img = val
      this.ruleForm.picUrl = val;
      // console.log(this.ruleForm.picUrl);
      this.$refs.upd.clearFiles();
      this.$message({
        type: "success",
        message: "上传成功!",
      });
    },
    //上传失败
    errorUp(val){
      this.$message({
        type: "error",
        message: "上传失败!",
      });
    },
    //上传图片验证
    beforeUpd(file) {
      // console.log(file);
      let testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      const fileType =
        testmsg.toLowerCase() === "jpg" ||
        testmsg.toLowerCase() === "jpeg" ||
        testmsg.toLowerCase() === "png";
      const fileLimit = file.size / 1024 < 500;
      if (!fileType) {
        this.$message({
          message: "上传图片只能是jpg / png 格式!",
          type: "error",
        });
        return false; //必须加上return false; 才能阻止
      }
      if (!fileLimit) {
        this.$message({
          message: "上传文件大小不能超过 500k!",
          type: "error",
        });
        return false;
      }
      return fileLimit || fileType;
    },
  },
};
</script>

<style scoped lang="scss">
.add {
  ::v-deep.el-card__header {
    padding: 0 20px 20px;
  }
  img {
    width: 100px;
    height: 100px;
    object-fit: contain;
  }
  h2 {
    margin: 0;
  }
  .ipt {
    width: 400px;
  }
  .el-icon-warning {
    margin-left: 20px;
    color: #e6a23c;
  }
}
</style>
